package cn.neusoft.config;

import cn.neusoft.interceptor.LoginInterceptor;
import cn.neusoft.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${alloworigins}")
    String[] allowOrigins;


    /**
     *  相当于前面SSM项目中写的跨域过滤器的作用
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        /**
         * addMapping:配置可以被跨域的路径，可以任意配置，可以具体到直接请求路径。
         * allowCredentials：是否开启Cookie
         * allowMethods：允许的请求方式，如：POST，GET，PUT，DELETE等。
         * allowOrigins：允许访问的url，可以固定单条或者多条内容。
         * allowedHeaders：允许的请求header，可以自定义设置任意请求头信息。
         * maxAge：配置预检请求的有效时间
         */
        registry.addMapping("/**")
                .allowedOrigins(allowOrigins)
//                .allowedOrigins("http://localhost:8899/","http://localhost:8888/","http://localhost:9999/") //前端地址
                .allowCredentials(true)
                .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
                .allowedHeaders("*")
                .maxAge(36000);
    }

    @Value("${uploadlocation}")
    String uploadlocation;

    /**
     * 相当于 springmvc.xml中配置的
     * <mvc:resources mapping="/img/**" location="file:D://upload1118/"/>
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("上传路径："+uploadlocation);
        registry.addResourceHandler("/img/**")
                .addResourceLocations("file:///"+uploadlocation);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/**");
//        registry.addInterceptor(new LoginInterceptor())
//                .addPathPatterns("/**")
//                .excludePathPatterns("/log/in");
    }
}
